<template>
  <div>
    <div class="container">
      <div>
        <el-input
          v-model="name"
          :placeholder="$t('formgen.formQuestion.searchInput')"
          class="question-bank-input"
          clearable
          size="default"
        >
          <template #append>
            <el-button
              icon="ele-Search"
              size="default"
              @click="searchTopic"
            />
          </template>
        </el-input>
        <el-button
          class="mb10"
          size="small"
          type="primary"
          @click="handleBatchImport"
        >
          {{ $t("formgen.formQuestion.batchImport") }}
        </el-button>
      </div>
      <div>
        <div class="title-top">
          <div class="title">{{ $t("formgen.formQuestion.myQuestions") }}</div>
          <div class="icon-group">
            <i
              class="refresh-icon"
              @click="getList"
            >
              <el-icon size="16">
                <ele-Refresh />
              </el-icon>
            </i>
            <i @click="handleAdd">
              <el-icon size="16">
                <ele-Plus />
              </el-icon>
            </i>
          </div>
        </div>
        <el-tree
          ref="personalQuestionTreeRef"
          :data="personalQuestionTreeData"
          :load="loadNode"
          :props="props"
          lazy
          node-key="nodeId"
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span class="label">{{ node.label }}</span>
              <span class="mr6">{{ data.itemCount }}</span>
              <span class="controls">
                <el-icon
                  v-if="node.level === 1"
                  class="text-primary"
                  @click.stop="handleUpdate(node)"
                >
                  <ele-Edit />
                </el-icon>
                <el-icon
                  class="text-danger"
                  @click.stop="handleDelete(node, data)"
                >
                  <ele-Delete />
                </el-icon>
              </span>
            </span>
          </template>
        </el-tree>
      </div>
      <div>
        <div class="title-top">
          <div class="title">{{ $t("formgen.formQuestion.commonQuestions") }}</div>
        </div>
        <el-tree
          :data="publicQuestionTreeData"
          :load="loadNode"
          :props="props"
          lazy
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span class="label">{{ node.label }}</span>
              <span class="mr6">{{ data.itemCount }}</span>
            </span>
          </template>
        </el-tree>
      </div>
    </div>
    <AddQuestionBankDialog
      ref="addQuestionBankRef"
      @refresh="getList"
    />
    <QuestionBankDialog ref="batchImportRef" />
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import {
  deleteQuestionBankById,
  getQuestionBankInfo,
  getQuestionBankItems,
  QuestionBank,
  searchQuestionBankItems
} from "@/api/question/bank";
import { delQuestionBankItemById, getQuestionBankItem, QuestionBankItem } from "@/api/question/bankItem";
import AddQuestionBankDialog from "./QuestionBankCreate.vue";
import { i18n } from "@/i18n";
import { MessageUtil } from "@/utils/messageUtil";
import QuestionBankDialog from "./QuestionBankDialog.vue";

const personalQuestionTreeData = ref<Record<string, any>[]>([]);
const publicQuestionTreeData = ref<Record<string, any>>([]);
const name = ref();

// 获取题库数据
const getList = async () => {
  const convertTreeNode = (item: any) => {
    return {
      id: item?.id,
      label: item?.name,
      leaf: !item?.itemCount,
      itemCount: item?.itemCount,
      nodeId: "bank" + item?.id
    };
  };

  const res = await getQuestionBankInfo();
  // 将获取到的数据保存到personalQuestionBank和publicQuestionBank
  personalQuestionTreeData.value = res.data.personalQuestionBanks!.map((item: QuestionBank) => convertTreeNode(item));
  publicQuestionTreeData.value = res.data.publicQuestionBanks!.map((item: QuestionBank) => convertTreeNode(item));
};

const props = {
  label: "label",
  children: "children",
  isLeaf: "leaf"
};

const convertItemToTreeNode = (item: any, bankId: number) => {
  return { id: item.id, label: item.label, bankId: bankId, leaf: true, nodeId: "item" + item.id };
};

const loadNode = (node: any, resolve: (data: any[]) => void, reject: () => void) => {
  const bankId = node?.data?.id;
  if (!bankId) {
    return resolve([]);
  }
  getQuestionBankItems(bankId)
    .then(res => {
      return resolve(res.data.map(item => convertItemToTreeNode(item, bankId)));
    })
    .catch(() => {
      return reject();
    });
};

const searchTopic = async () => {
  if (!name.value) {
    getList();
    return;
  }
  // 根据name查询
  const res = await searchQuestionBankItems(name.value);
  personalQuestionTreeData.value = res.data.personalQuestionBankItems.map((item: QuestionBankItem) =>
    convertItemToTreeNode(item, 100)
  );
  publicQuestionTreeData.value = res.data.publicQuestionBankItems.map((item: QuestionBankItem) =>
    convertItemToTreeNode(item, 100)
  );
};
const handleAdd = async () => {
  addQuestionBankRef.value.showDialog();
};
const handleUpdate = async (node: any) => {
  addQuestionBankRef.value.showDialog(node);
};

const addQuestionBankRef = ref();

const personalQuestionTreeRef = ref();

const handleDelete = async (node: any, data: any) => {
  console.log(personalQuestionTreeData.value);
  const id = node.data.id;
  if (node.data.bankId) {
    await delQuestionBankItemById(id);
  } else {
    await deleteQuestionBankById(id);
  }
  personalQuestionTreeRef.value.remove(data.nodeId);
  MessageUtil.success(i18n.global.t("formI18n.all.success"));
};

const emit = defineEmits(["add"]);

const handleNodeClick = async (data: QuestionBankItem) => {
  if (!data?.bankId) {
    return;
  }
  const item = await getQuestionBankItem(data.id as number);
  emit("add", item.data.scheme);
};

const batchImportRef = ref();

const handleBatchImport = () => {
  batchImportRef.value.showDialog();
};

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
.container {
  overflow-y: scroll;
  height: calc(100vh - 85px);
}

.question-bank-input {
  width: 260px;
  margin: 10px auto;
}

.title-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  line-height: 23px;

  .title {
    font-size: 14px;
    font-weight: 600;
  }

  .icon-group {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  i {
    color: var(--el-color-primary);
    cursor: pointer;
    vertical-align: middle;
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  .label {
    // 超出省略
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 170px;
  }
}

.custom-tree-node .controls {
  display: none;
}

.custom-tree-node:hover .controls {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
